package lk.exception;

import lk.util.SessionUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局json封装
 */
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice {
    /**
     * <del>固定为 json 解析规则</del>
     */
    @Override
    public boolean supports(@Nullable MethodParameter methodParameter, @Nullable Class converterType) {
        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object o, @NonNull MethodParameter methodParameter, @NonNull MediaType mediaType, @NonNull Class selectedConverterType, @NonNull ServerHttpRequest serverHttpRequest, @NonNull ServerHttpResponse serverHttpResponse) {

        //返回值封装跳过swagger的默认访问接口
        String url = SessionUtil.getRequest().getRequestURI();
        if (url.contains("/swagger-resources") || url.contains("/v2/api-docs")) {
            return o;
        }

        if (o != null) {
            if (o instanceof lk.exception.RestfulRecord) {
                return o;
            }

            RestfulRecord restfulRecord = new RestfulRecord();
            if (o instanceof String) {
                restfulRecord.setData(o);
                restfulRecord.setMsg("成功");
                return restfulRecord;
            } else {
                //数据
                restfulRecord.setData(o);
                restfulRecord.setMsg("成功");
            }
            return restfulRecord;
        }
        return new RestfulRecord();
    }

}
